package com.gsi.webstore.platform.storefront.pipelet.shipping;

import java.util.Iterator;

import com.intershop.beehive.core.capi.component.ComponentMgr;
import com.intershop.beehive.core.capi.naming.NamingMgr;
import com.intershop.beehive.core.capi.pipeline.Pipelet;
import com.intershop.beehive.core.capi.pipeline.PipelineDictionary;
import com.intershop.beehive.core.capi.pipeline.PipeletExecutionException;
import com.intershop.beehive.bts.capi.orderprocess.LineItem;
import com.intershop.beehive.bts.capi.orderprocess.ProductLineItem;
import com.intershop.beehive.bts.capi.orderprocess.basket.Basket;
import com.intershop.component.shipping.capi.defaultshippingmethodprovider.DefaultShippingMethodProvider;
import com.intershop.component.shipping_data.capi.shippingmethod.ShippingMethod;

/**
 * Set the default shipping method for all LineItems in the Basket provided if
 * there is no shipping method selected. For LineItems that have a shipping
 * method set, nothing is changed.
 */
public class SetDefaultShippingMethod extends Pipelet
{

    /**
     * Constant used to access the pipeline dictionary with key 'Basket'
     * 
     * The shopping cart
     */
    public static final String DN_BASKET = "Basket";

    /**
     * The pipelet's execute method is called whenever the pipelets gets
     * executed in the context of a pipeline and a request. The pipeline
     * dictionary valid for the currently executing thread is provided as a
     * parameter.
     * 
     * @param dict
     *            The pipeline dictionary to be used.
     * @throws PipeletExecutionException
     *             Thrown in case of severe errors that make the pipelet execute
     *             impossible (e.g. missing required input data).
     */
    public int execute(PipelineDictionary dict)
    throws PipeletExecutionException {        
        // lookup 'Basket' in pipeline dictionary
        Basket basket = (Basket)dict.get(DN_BASKET);
        if (null == basket)
        {
            throw new PipeletExecutionException("Mandatory input parameter 'Basket' not available in pipeline dictionary.");
        }
        
        ComponentMgr compMgr = (ComponentMgr)NamingMgr.getManager(ComponentMgr.class);
        DefaultShippingMethodProvider provider = 
            (DefaultShippingMethodProvider)compMgr.getComponent("defaultShippingMethodProvider");
        
        Iterator<ProductLineItem> lineItems = basket.createProductLineItemsIterator();
        while (lineItems != null && lineItems.hasNext()) {
            ProductLineItem lineItem = lineItems.next();
            ShippingMethod defaultShippingMethod = provider.getDefaultShippingMethod(lineItem);
            lineItem.setShippingMethod(defaultShippingMethod);
          
        }

        return PIPELET_NEXT;
    }
}